#!/usr/bin/env python

"""
        __author__      = "Vishal Patil"
        __copyright__   = "Copyright (C) 2006 Vishal Patil"
"""

#
#	A simple python implementation of TSP (Traveling Salesman Problem) using PGAP
#	The user as to provide a simple distance map as shown below. The key for the map
#	is the city name while the value is another dictionary of city names and 
#	corresponding distances.	 
#

import sys
from pgap import RandomGenerator
from pgap.impl.CrossoverMutateOperator import CrossoverMutateOperator
from pgap.impl.BestChromosoneSelector import BestChromosonesSelector
from pgap.Configuration import Configuration
from pgap.Genotype import Genotype
from pgap.impl.TSP import TSPChromosone

distanceMap = {
		'A' : {'D': 15, 'E': 20},
		'B' : {'C': 20, 'D': 25, 'E': 20},
		'C' : {'B': 20, 'D': 15, 'E': 20},
		'D' : {'A': 15, 'B': 25, 'C': 15, 'E': 20},
		'E' : {'A': 20, 'B': 20, 'C': 20, 'D': 20}
	      }


#
#       Solving a problem using PGAP involes the following steps
#       1) Create an appropriate Chromosone class for the problem
#       2) Create a configuration object and set the initial population 
#       3) Create genetic operators and add them to the configuration
#       4) Create chromosone selectors and add them to the configuration
#       5) Create a Genotype using the configuration
#       6) Create chromosones, twice the population size, initialize them
#          to random values and add them to the population               
#       7) Now keep on evovling the genotype until the chromosone of desire
#          fitness is obtained
#

def main():
	configuration = Configuration()

	configuration.setPopulationSize(50)

	crossoverOp = CrossoverMutateOperator()
	configuration.addGeneticOperator(crossoverOp)		

	chromosoneSel = BestChromosonesSelector()
	configuration.addNaturalSelector(chromosoneSel)	

	geno	= Genotype(configuration)

	for i in range(0,2*geno.getPopulation().getPopulationSize()):
		tspChromosone = TSPChromosone(distanceMap)
		tspChromosone.setRandomValue()
		geno.getPopulation().addChromosone(tspChromosone)

	
	for i in range(0,10):
		geno.evolve()
		geno.getPopulation().getChromosones().sort()
		print geno.getPopulation().getChromosones()[0]

if __name__ == "__main__":
	main()
